<?php

namespace App\Http\Controllers\Api\V1;

use Auth;
use App\Models\User;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Api\Controller;
use App\Http\Requests\Api\V1\SocialAuthorizationRequest;
use App\Http\Requests\Api\V1\AuthorizationRequest;

class AuthorizationsController extends Controller
{
    use Helpers;

    public function store(AuthorizationRequest $request)
    {
        $username = $request->username;

        filter_var($username, FILTER_VALIDATE_EMAIL) ?
            $credentials['email'] = $username :
            $credentials['name'] = $username;

        $credentials['password'] = $request->password;
        $key = $request->key;

        $apiKey = $this->verify($username, $key);
        if ($key != $apiKey) {
            \Log::info('aaa:'.$key);
            \Log::info('bbb:'.$apiKey);
            \Log::info('ccccc:');
            return $this->respondError(500, '错误参数key');
        } else {
            if (isset($apiKey['status_code'])) {
                return $apiKey;
            }
        }

        if (!$token = \Auth::guard('api')->claims(['key' => $apiKey])->attempt($credentials)) {
            return $this->respondError(500, '用户名或密码错误');
        }

        return $this->respondWithToken($token)->setStatusCode(200);
    }

    public function update()
    {
        $token = \Auth::guard('api')->refresh();
        return $this->respondWithToken($token);
    }

    public function destroy()
    {
        \Auth::guard('api')->logout();
        return $this->response->noContent();
    }

    public function socialStore($type, SocialAuthorizationRequest $request)
    {
        if (!in_array($type, ['weixin'])) {
            return $this->response->errorBadRequest();
        }

        $driver = \Socialite::driver($type);

        try {
            if ($code = $request->code) {
                $response = $driver->getAccessTokenResponse($code);
                $token = array_get($response, 'access_token');
            } else {
                $token = $request->access_token;

                if ($type == 'weixin') {
                    $driver->setOpenId($request->openid);
                }
            }

            $oauthUser = $driver->userFromToken($token);
        } catch (\Exception $e) {
            return $this->response->errorUnauthorized('参数错误，未获取用户信息');
        }

        switch ($type) {
            case 'weixin':
                $unionid = $oauthUser->offsetExists('unionid') ? $oauthUser->offsetGet('unionid') : null;

                if ($unionid) {
                    $user = User::where('weixin_unionid', $unionid)->first();
                } else {
                    $user = User::where('weixin_openid', $oauthUser->getId())->first();
                }

                // 没有用户，默认创建一个用户
                if (!$user) {
                    $user = User::create([
                            'name' => $oauthUser->getNickname(),
                            'avatar' => $oauthUser->getAvatar(),
                            'weixin_openid' => $oauthUser->getId(),
                            'weixin_unionid' => $unionid,
                        ]
                    );
                }

                break;
        }

        $token = \Auth::guard('api')->fromUser($user);

        return $this->respondWithToken($token)->setStatusCode(201);
    }

    protected function respondWithToken($token)
    {
        return $this->response->array([
                'status_code' => 200,
                'message' => '',
                'data' => [
                    'access_token' => $token,
                    'token_type' => 'Bearer',
                    'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
                ]
            ]
        );
    }


    protected function verify($username, $key)
    {
        $user = User::where('name', $username)->first();

        if (empty($user))
            return $this->respondError(500, '用户不存在');
        if ($user->type != 2)
            return $this->respondError(500, '非网站用户');

        $site = $user->site;
        if (encrypt($username . $site->username) == $key) {
            return $this->respondError(500, '非法参数key');
        }
        $token = $site->token;
        return $token;
    }

    protected function respondError($status_code, $message)
    {
        return $this->response->array([
                'status_code' => $status_code,
                'message' => $message
            ]
        );
    }
}
